<template>
  <div>
    <a-modal
      ok-text="确认"
      cancel-text="取消"
      :maskClosable="false"
      :title="title + 'BOM'"
      :width="modalWidth"
      @cancel="handleClose"
      :destroyOnClose="true"
      @ok="handleOk"
      :visible="visible"
      :confirmLoading="confirmLoading"
      footer=""
    >
      <template>
        <div class="modalBut">
          <a-button @click="handleClose">
            取消
          </a-button>
          <a-button @click="handleOk" type="primary">确认</a-button>
        </div>
      </template>
      <a-spin :spinning="confirmLoading">
        <a-form-model ref="ruleForm" :model="model" :rules="rules">
          <a-form-model-item
            v-if="title === '新增'"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            style="margin-bottom:0"
            label="关联商品"
            prop="goodsId"
            hasFeedback
          >
            <a-row>
              <a-col>
                <a-select
                  :open="false"
                  :defaultOpen="false"
                  mode="multiple"
                  :allowClear="true"
                  placeholder="关联商品"
                  v-model.trim="model.goodsId"
                  @dropdownVisibleChange="handleTableSelect"
                  @change="handleGoodChange"
                >
                  <a-select-option
                    v-for="item in tableOption"
                    :key="item.id"
                    :value="item.id"
                  >
                    {{ item.goodsName }}
                  </a-select-option>
                </a-select>
              </a-col>
            </a-row>
          </a-form-model-item>

          <a-form-model-item
            v-else
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            style="margin-bottom:0"
            label="关联商品"
            prop="copyGoodsId"
            hasFeedback
          >
            <a-row>
              <a-col>
                <a-select
                  :open="false"
                  :defaultOpen="false"
                  mode="multiple"
                  :allowClear="true"
                  placeholder="关联商品"
                  v-model.trim="model.copyGoodsId"
                  @dropdownVisibleChange="handleTableSelect"
                >
                  <a-select-option
                    v-for="item in tableOption"
                    :key="item.id"
                    :value="item.id"
                  >
                    {{ item.goodsName }}
                  </a-select-option>
                </a-select>
              </a-col>
            </a-row>
          </a-form-model-item>
        </a-form-model>
      </a-spin>

      <TableSelectModal
        :columns="columns"
        :replaceFields="replaceFields"
        :treeKey="treeKey"
        :tableKey="tableKey"
        :searchKey="searchKey"
        :name="name"
        :code="code"
        :filename="filename"
        ref="tableModal"
        @tableSelect="tableSelect"
      ></TableSelectModal>
    </a-modal>
  </div>
</template>

<script>
import api from "@/api/apiServer";
import TableSelectModal from "@/components/TableSelectModal";
import { goodColumns } from "./tableConfig";
export default {
  components: { TableSelectModal },
  props: {
    treeData: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      title: "", // 标题
      visible: false, // 状态、
      modalWidth: 652, // 抽屉宽度
      model: {},
      goodsOption: [], // 商品选择数据源
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,

      // 选中组件参数
      replaceFields: {
        children: "goodsTypeList",
        title: "goodsTypeName",
        key: "id",
        value: "id",
      },
      treeKey: "CommodityTypeFindAll",
      tableKey: "CommodityList",
      searchKey: "goodsType",
      name: "goodsName",
      code: "goodsCode",
      columns: goodColumns,
      filename: "CommodityModal",
      tableOption: [],
    };
  },
  computed: {
    rules() {
      return {
        goodsId: [
          { required: true, message: "请选择关联商品", trigger: "change" },
        ],
        copyGoodsId: [
          { required: true, message: "请选择关联商品", trigger: "change" },
        ],
      };
    },
  },
  mounted() {},
  methods: {
    // 商品查询
    handleSearch(goodsName) {
      this.getGoodList(goodsName);
    },
    // 获取商品列表
    async getGoodList(goodsName) {
      let params = { pageNumber: 1, pageSize: 10 };
      if (goodsName) {
        params.goodsName = goodsName;
        const res = await api.CommodityList(params);
        this.goodsOption = res.data.data;
      }
    },
    tableSelect(result, tableOption) {
      this.tableOption = tableOption;

      let goodIds = [];
      result.forEach((item) => {
        goodIds.push(item.id);
      });
      if (this.title === "复制") {
        this.$set(this.model, "copyGoodsId", goodIds);
        return;
      }
      this.$set(this.model, "goodsId", goodIds);
    },
    handleTableSelect() {
      this.$refs.tableModal.title = "商品";
      this.$refs.tableModal.modalAdd();
      if (this.model.goodsId) {
        let arr = this.model.goodsId.toString().split(",");
        if (arr.length > 0) {
          let newArr = arr.map((item) => {
            return Number(item);
          });
          this.$refs.tableModal.selectedRowKeys = newArr;
        } else {
          this.$refs.tableModal.selectedRowKeys = [];
        }
      }
      if (this.model.copyGoodsId) {
        let arr = this.model.copyGoodsId.toString().split(",");
        if (arr.length > 0) {
          let newArr = arr.map((item) => {
            return Number(item);
          });
          this.$refs.tableModal.selectedRowKeys = newArr;
        } else {
          this.$refs.tableModal.selectedRowKeys = [];
        }
      }
    },
    handleGoodChange(value) {
      if (value.length > 0) {
        if (this.model.goodsId) {
          this.model.goodsId = value.toString();
        }
        if (this.model.copyGoodsId) {
          this.model.copyGoodsId = value.toString();
        }
      } else {
        if (this.model.goodsId) {
          delete this.model.goodsId;
        }
        if (this.model.goodsId) {
          delete this.model.copyGoodsId;
        }
      }
    },

    // 新增
    modalAdd() {
      this.modalEdit(this.model);
    },
    // 编辑
    modalEdit(record) {
      this.resetScreenSize();
      this.visible = true;
      if (this.title === "复制") {
        this.$set(this.model, "id", record.id);
      }
    },

    async submitVulFun() {
      this.confirmLoading = true;
      if (this.model.goodsId) {
        let newArr = this.model.goodsId;
        this.$set(this.model, "goodsId", Number(newArr.toString()));
      }
      if (this.model.copyGoodsId) {
        let newArr = this.model.copyGoodsId;
        this.$set(this.model, "copyGoodsId", Number(newArr.toString()));
      }
      let res;
      if (this.title === "新增") {
        res = await api.ProductAddOrUpdate(this.model);
      } else {
        res = await api.ProductCopy(this.model);
      }
      if (res.code && res.code !== 200) {
        this.$message.error(res.message);
        this.confirmLoading = false;
        return;
      }
      this.$message.success(res.message);
      this.confirmLoading = false;
      this.$emit("ok");
      this.model = Object.assign({});
      this.visible = false;
    },
    handleOk() {
      const that = this;
      // 触发表单验证
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          that.submitVulFun();
        } else {
          return false;
        }
      });
    },
    // 关闭
    handleClose() {
      this.visible = false;
      this.model = Object.assign({});
      this.$refs.ruleForm.resetFields();
    },
    // 根据屏幕变化,设置抽屉尺寸
    resetScreenSize() {
      let screenWidth = document.body.clientWidth;
      if (screenWidth < 500) {
        this.modalWidth = screenWidth;
      } else {
        this.modalWidth = 652;
      }
    },
  },
};
</script>

<style scoped lang="less">
::v-deep .ant-form-item-children-icon {
  display: none !important;
}
</style>
